<template>
	<div>
		<el-row>
			<h3>我的购物车(共{{cartList.length}}件商品)</h3>
		</el-row>
		<el-table :data="cartList" 
			style="width: 100%;" 
			@select="selectOrder" 
			@select-all="selectOrder"
			:row-key="(row)=>{return row.cart.id}"
			>
			<el-table-column type="selection" :reserve-selection="true"/>
			<el-table-column label="编号" prop="cart.bookid" align="center" :width="60"/>
			<el-table-column label="图片" :width="100" align="center">
				<template #default="scope">
					<el-avatar shape="square"
						:src="`${$ServerUrl}/api/public/showImg/${scope.row.book.picture}`">
					</el-avatar>
				</template>
			</el-table-column>
			<el-table-column label="名称" prop="book.name"></el-table-column>
			<el-table-column label="单价" prop="book.price" align="center"></el-table-column>
			<el-table-column label="数量" prop="cart.num" align="center" >
				<template #default="scope">
					<el-input-number v-model="scope.row.cart.num" :min="1"  />
				</template>
			</el-table-column>
			<el-table-column label="总价" align="center">
				<template #default="scope">
					{{scope.row.book.price * scope.row.cart.num}}
				</template>
			</el-table-column>
		</el-table>
		<el-row>
			<el-col>总价：{{totalPrice}}</el-col>
		</el-row>
		<el-row>
			<el-button type="danger" @click="addOrder()">去下单</el-button>
		</el-row>
	</div>
</template>

<script>
import { ElMessage } from 'element-plus'
export default{
	name:'Main',
	data(){
		return {
			cartList:[],//商品列表
			selectList:[],//已选中商品
		}
	},
	methods:{
		selectOrder(selection){
			this.selectList = selection;
		},
		//去下单
		addOrder(){
			if(this.selectList.length<1){
				ElMessage({
					message: '请选中需要下单的商品！',
				})
				return false;
			}
			this.$store.commit('setOrders',this.selectList)
			this.$router.push({'name':'cart_make'});
		}
	},
	mounted() {
		this.axios.get('/api/fore/cart/findAll',{
			headers : { 'Authorization' : localStorage.token_type+' '+ localStorage.token}
		}).then((res)=>{
			let data = res.data;
			if(data.code==200){
				this.cartList = data.data;
				// console.log(this.cartList);
			}else{
				
			}
			
		}).catch((err)=>{
			console.log(err);
		})
	},
	computed:{
		totalPrice(){
			//计算总价，判断已选中商品比对商品列表的购物车标识是否一致，一致就计算总价
			let num = 0;
			for(let sList of this.selectList){
				for(let cList of this.cartList){
					if(sList.cart.id == cList.cart.id){
						num += (sList.book.price * sList.cart.num)
					}
				}
			}
			return num;
		}
	}
}
</script>

<style scoped>

</style>
